package com.esteel.settlement.service;

import java.nio.charset.Charset;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.esteel.settlement.entity.TbSettPacketLog;
import com.esteel.settlement.pa.packet.BusinessHeader;
import com.esteel.settlement.pa.packet.PacketHeader;

@Component
public class PacketLogger {

	@Autowired
	private SettPacketLogService settPacketLogService;
	
	private static PacketLogger logger;
	
	@PostConstruct
	public void init(){
		logger = this;
		logger.settPacketLogService = this.settPacketLogService;
	}
	
	public static void log(String packetStr){
		byte[] src = packetStr.getBytes(Charset.forName("GBK")); 
		
		TbSettPacketLog tbLog = new TbSettPacketLog();
		
		//分析报文头
		byte[] phsrc = new byte[222];
		System.arraycopy(src, 0, phsrc, 0, phsrc.length);
		if (src.length>=222){
			PacketHeader ph = new PacketHeader();
			ph.analyze(src);
			tbLog.setLogNo(ph.getThirdLogNo());
			tbLog.setTranDate(ph.getTranDate());
			tbLog.setRspCode(ph.getRspCode());
			tbLog.setPacket(packetStr);
		}

		
		if (src.length>=344){
			//分析业务报文头
			byte[] bhsrc = new byte[122];
			System.arraycopy(src, 222, bhsrc, 0, bhsrc.length);
			BusinessHeader bh = new BusinessHeader();
			bh.analyze(bhsrc);
			tbLog.setTranFunc(bh.getTranFunc());
		}
		
		logger.settPacketLogService.add(tbLog);
	}
	
	
}
